package com.plm.k8s.myk8sapi.cmd.impl;

import com.plm.k8s.myk8sapi.cmd.AbstractLocalCmd;
import com.plm.k8s.myk8sapi.cmd.ILogCmd;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author 潘磊明
 * 版本号：1.0
 * 创建日期：2021/9/2 15:37
 */
@Service
public class LogCmdImpl extends AbstractLocalCmd implements ILogCmd {

    @Override
    public List<String> getLogs(String resource, String name, String namespace, String containerName) throws Exception {
        if (!StringUtils.hasText(name)) throw new Exception("资源名称不能为空！");
        String tmpResource = !StringUtils.hasText(resource) ? "pod" : resource; // 默认pod资源
        String cmd = generateLogCmd(tmpResource, name, namespace, containerName);
        return execForLine(cmd);
    }

    /**
     * 生成日志信息命令
     * @param tmpResource
     * @param name
     * @param containerName
     * @return
     */
    private String generateLogCmd(String tmpResource, String name, String namespace, String containerName) {
        StringBuilder sb = new StringBuilder(generateKubeCmdBase());
        sb.append(String.format("logs %s/%s", tmpResource, name));
        addNamespace(sb, namespace);
        if (StringUtils.hasText(containerName)) {
            sb.append(CMD_DELIMITER).append("-c ").append(containerName);
        }
        return sb.toString();
    }
}
